import math
from django.db import models
from django.contrib.auth.models import User
from django.utils.text import Truncator
from django.utils.html import mark_safe

from markdown import markdown


class Board(models.Model):
    name = models.CharField(max_length=30, unique=True)
    description = models.CharField(max_length=100)

    def __str__(self):
        return self.name

    def get_post_count(self):
        return Post.objects.filter(topic__board=self).count()

    def get_last_post(self):
        return Post.objects.filter(topic__board=self).order_by('-create_by').first()


class Topic(models.Model):
    subject = models.CharField('主题', max_length=255)
    last_update = models.DateTimeField(auto_now_add=True)  # auto_now_add 自动添加添加对象的时间
    board = models.ForeignKey(Board, related_name='topics')
    starter = models.ForeignKey(User, related_name='topics')
    views = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.subject

    def get_page_count(self):
        count = self.posts.count()
        page = count / 8
        return math.ceil(page)

    def has_many_page(self, count=None):
        if count is None:
            count = self.get_page_count()
        return count > 5

    def get_page_range(self):
        count = self.get_page_count()
        if self.has_many_page(count):
            return range(1, 4)
        return range(1, count+1)

    def get_last_eight_posts(self):
        return self.posts.order_by('-create_at')[:8]


class Post(models.Model):
    message = models.TextField('消息', max_length=4000)
    topic = models.ForeignKey(Topic, related_name='posts')
    create_at = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(null=True)
    create_by = models.ForeignKey(User, related_name='posts')
    update_by = models.ForeignKey(User, null=True, related_name='+')

    def __str__(self):
        truncated_message = Truncator(self.message)
        return truncated_message.chars(30)

    def get_message_as_markdown(self):
        return mark_safe(markdown(self.message, safa_mode='escape'))
